﻿using System;
using System.Data;
using System.Data.Common;
using System.Web.UI.WebControls;
using System.Linq;
using System.Web.Security;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;

public partial class Backend_Category_Add : System.Web.UI.Page
{
	public static readonly string[] VALID_EXTENSIONS = new string[4] { ".png", ".jpg", ".gif", ".jpeg" };

	protected void Page_Load(object sender, EventArgs e)
	{
		this.Title = "គ្រប់គ្រងមុខម្ហូប - " + ElegantFoodConfiguration.SiteName;
		this.Form.Action = "Backend/Product/Add.aspx";
		if (!IsPostBack)
		{
			DbCommand cmd = GenericDataAccess.CreateCommand();
			cmd.CommandText = "EF_GetCategoryByStatus";

			Category.DataSource = GenericDataAccess.ExecuteSelectCommand(cmd);
			Category.DataTextField = "Name";
			Category.DataValueField = "CategoryID";
			Category.DataBind();
		}
	}


	protected void Save_Click(object sender, EventArgs e)
	{
		string[] CategorySelected = Category.Items.Cast<ListItem>().Where(item => item.Selected).Select(item => item.Value).ToArray();

		if (IsValidAllowExtension())
		{
			//if (!EF_Product.checkDuplicatedProductName(Name.Text))
			//{
				EF_ProductProperty product = new EF_ProductProperty();
				product.UserID = ElegantFoodConfiguration.CurrentLoginUserID;
				product.Name = Name.Text;
				product.Price = decimal.Parse(Price.Text);
				if (SpecialPrice.Text != "")
					product.SpecialPrice = decimal.Parse(SpecialPrice.Text);
				else
					product.SpecialPrice = decimal.Parse("0");
				
				product.Description = Description.Text;
				product.HightLight = HightLight.Checked;
				product.Promotion = Promotion.Checked;
				product.Status = Status.Checked;
				string filename = DoUpload(399, "~/Uploads");
				product.Image = filename;
				product.Thumbnail = filename;
				int ProductID = EF_Product.CreateProduct(product);

				// Assign product to category
				if (ProductID > 0)
				{
					EF_Product.AssignProductToCategory(ProductID, CategorySelected);
					Response.Redirect("Default.aspx");
				}
			//}
			//else
			//{
			//	DisplayNameError.Text = "ឈ្មោះម្ហូបនេះមានរួចហើយ!";
			//}
		}
		else
		{
			DisplayUploadError.Text = "Only jpg, png and gif are allowed!";
		}
	}

	// Upload Image
	private string DoUpload(int width, string dir)
	{
		string filename;
		string originalName = Image.FileName;
		filename = originalName.Replace(" ", "").ToLower();

		// Check directory
		DirectoryInfo upload = new DirectoryInfo(Server.MapPath(dir));
		if (!upload.Exists)
		{
			upload.Create();
		}

		string dirUpload = Server.MapPath(dir + "/");

		// Create a bitmap of the content upload control in memory
		Bitmap originalBMP = new Bitmap(Image.FileContent);
		float ratio = 0;
		float orginalWidth = originalBMP.Width;
		float orignalHeight = originalBMP.Height;
		if (orignalHeight > orginalWidth)
		{
			ratio = orignalHeight / orginalWidth;
		}
		else
		{
			ratio = orginalWidth / orignalHeight;
		}

		int newWidth = width;
		int newHeight = (int)(newWidth / ratio);

		// Create a new bitmap to hold the provious resized bitmap
		Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);

		// create graphic based on the new bitmap
		Graphics graphic = Graphics.FromImage(newBMP);

		// Set the properties for the new graphic file
		graphic.SmoothingMode = SmoothingMode.AntiAlias;
		graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

		// Draw the new graphic based on the resized bitmap
		graphic.DrawImage(originalBMP, 0, 0, newWidth, newHeight);

		// Get image name from directory
		string tmpfname = Path.Combine(Server.MapPath(dir), filename);

		// Check existing image
		string name;
		string extension;
		if (File.Exists(tmpfname))
		{
			int j = 1;
			extension = Path.GetExtension(filename);
			while (File.Exists(dirUpload + filename))
			{
				name = Path.GetFileNameWithoutExtension(filename);
				filename = name + "-" + j + extension;
			}
		}

		// Save image to directory
		newBMP.Save(dirUpload + filename, ImageFormat.Jpeg);
		originalBMP.Dispose();
		newBMP.Dispose();
		graphic.Dispose();

		// Create thumbnail
		if (width > 253)
		{
			this.DoUpload(253, "~/Uploads/Thumbnails");
		}

		return filename;
	}

	// Check valid upload file
	private bool IsValidAllowExtension()
	{
		string extension = Path.GetExtension(Image.FileName);
		if (!VALID_EXTENSIONS.Contains(extension.ToLower()))
		{
			return false;
		}
		return true;
	}
}